package com.wingy.mysearchmanager;

import android.app.SearchManager;
import android.content.Intent;
import android.provider.SearchRecentSuggestions;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SearchResultActivity extends AppCompatActivity implements OnClickListener {

    private TextView tvquery, tvdata;
    private Button btnsearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);
        tvquery = (TextView) findViewById(R.id.tvquery);
        tvdata = (TextView) findViewById(R.id.tvdata);
        btnsearch = (Button)findViewById(R.id.btnsearch);

        doSearchQuery();

        btnsearch.setOnClickListener(this);
     }

     public void doSearchQuery() {
        final Intent intent = getIntent();
        String query = intent.getStringExtra(SearchManager.QUERY);
        tvquery.setText(query);

         SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this, SearchSuggestionSampleProvider.AUTHORITY, SearchSuggestionSampleProvider.MODE);
         suggestions.saveRecentQuery(query, null);
         if(Intent.ACTION_SEARCH.equals(intent.getAction())) {
             Bundle bundle = intent.getBundleExtra(SearchManager.APP_DATA);
             if(bundle != null) {
                 String ttdata = bundle.getString("data");
                 tvdata.setText(ttdata);
             }else{
                 tvdata.setText("no data");
             }
         }
     }

    @Override
    public void onClick(View v) {
        onSearchRequested();
    }

    @Override
    public boolean onSearchRequested() {
        startSearch("onNewIntent", false, null, false);
        return true;

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String query = intent.getStringExtra(SearchManager.QUERY);
        tvquery.setText(query);

        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this, SearchSuggestionSampleProvider.AUTHORITY, SearchSuggestionSampleProvider.MODE);

        suggestions.saveRecentQuery(query, null);

        if(Intent.ACTION_SEARCH.equals(intent.getAction())) {
            Bundle bundle = intent.getBundleExtra(SearchManager.APP_DATA);
            if(bundle != null) {
                String ttdata = bundle.getString("data");
                tvdata.setText(ttdata);
            }else{
                tvdata.setText("no data");
            }
        }
    }
}
